package com.baiyang.app.ui.login;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.baiyang.app.HomeActivity;
import com.baiyang.app.MyApp;
import com.baiyang.app.R;
import com.baiyang.app.databinding.ActivityLoginBinding;
import com.baiyang.app.model.User;
import com.baiyang.app.tool.LogUtils;
import com.baiyang.app.ui.register.RegisterActivity;

public class LoginActivity extends AppCompatActivity {

    private ActivityLoginBinding activityLoginBinding;
    private LoginViewModel loginViewModel;
    private LoginService loginService;
    private User user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityLoginBinding = DataBindingUtil.setContentView(this,R.layout.activity_login);
        user = new User();
        activityLoginBinding.setUser(user);
        loginViewModel = new ViewModelProvider(this).get(LoginViewModel.class);
        loginService = new LoginService(getApplication(),loginViewModel);
        init();
        initHandler();
    }

    private void initHandler() {
        loginViewModel.getLoginResult().observe(this, new Observer<JSONObject>() {
            @Override
            public void onChanged(JSONObject jsonObject) {
                String result = jsonObject.getString("result");
                if("SUCCESS".equals(result)){
                    User user = jsonObject.getObject("data",User.class);
                    // 将user存储到myapp
                    MyApp.getInstance().setUser(user);
                    Intent intent = new Intent();
                    intent.setClass(getApplicationContext(), HomeActivity.class);
                    startActivity(intent);
                    finish();
                    overridePendingTransition(R.anim.left_in,R.anim.right_out);
                }else{
                    String detail = jsonObject.getString("detail");
                    Toast.makeText(getApplicationContext(),detail,Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void init(){
        // 点击登录按钮
        activityLoginBinding.login.setOnClickListener(e->{
            loginService.login(user);
        });
        activityLoginBinding.register.setOnClickListener(e->{
            Intent intent = new Intent();
            intent.setClass(getApplicationContext(), RegisterActivity.class);
            startActivity(intent);
            overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        activityLoginBinding = null;
    }
}